import argparse
from contextlib import asynccontextmanager
from fastapi import FastAPI
from core.config.proxy import init_config, cfg  # Import the config functions
from core.logger.proxy import init_logger  # Import the logger functions
from core.thread.consumer import QueueConsumerThread
from router.api_router import api_router  # Import the router module
from router.middlewares import AccessLogMiddleware  # Import the middleware
from infrax.event import stop_event  # Import the global stop event
from infrax.queue import message_queue, message_queue_handler


# CLI 解析
parser = argparse.ArgumentParser()
parser.add_argument(
    "--config", required=False, help="Path to YAML config", default="config.yaml"
)
args, _ = parser.parse_known_args()

# 初始化配置
init_config(args.config)
# 初始化日志
init_logger(cfg.app.name, cfg.log)


# 初始化消费者线程
consumer = QueueConsumerThread(
    source=message_queue,
    handler=message_queue_handler,
    name="message-consumer",
    stop_event=stop_event,
    max_workers=4,
)
consumer.start()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # startup
    print("App starting...")
    yield
    # shutdown
    stop_event.set()
    consumer.join(timeout=5)
    print("App stopped.")


# FastAPI 初始化
app = FastAPI(title=cfg.app.name, lifespan=lifespan)
# 中间件注册
app.add_middleware(AccessLogMiddleware)
# 路由注册
app.include_router(api_router)


if __name__ == "__main__":
    import uvicorn

    print("Starting FastAPI app...")
    uvicorn.run(app, host=cfg.app.host, port=cfg.app.port)
